package utils;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
    
	private static SqlSessionFactory sqlSessionFactory;
	
	public static SqlSessionFactory getSqlSessionFactory(){
		if(sqlSessionFactory!=null){
			return sqlSessionFactory;
		}else{
			Reader reader = null;
			try {
				reader = Resources.getResourceAsReader("SqlMapConfig.xml");
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("Config file is not found");
				closeReader(reader);
			}
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			closeReader(reader);
			return sqlSessionFactory;
		}
	}
	
	public static SqlSession getSession(){
		SqlSession sqlSession = getSqlSessionFactory().openSession();
		return sqlSession;
	}
	
	public static void closeReader(Reader reader){
		try {
			if(reader!=null){
				reader.close();
				reader = null;
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
